﻿using SmartAgricultureService.Models.Enums;
using System.Collections.Concurrent;

namespace SmartAgricultureService.Core
{
    public sealed class HeartbeatQueue
    {
        private static HeartbeatQueue _instance;
        private readonly ConcurrentDictionary<string, DateTime> _queue;
        public static HeartbeatQueue Instance => _instance ??= new HeartbeatQueue();
        private HeartbeatQueue() => _queue = new ConcurrentDictionary<string, DateTime>();
        public void Update(string deviceId)
        {
            try
            {
                var status = _queue.ContainsKey(deviceId) ? HeartbeatStatus.Updated : HeartbeatStatus.Added;
                _queue.AddOrUpdate(deviceId, DateTime.Now, (_, _) => DateTime.Now);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("Update", ex);
            }
        }
        public void StartListen()
        {
            Task.Factory.StartNew(async () =>
            {
                foreach (var item in _queue)
                {
                    try
                    {
                        if (item.Value.CompareTo(DateTime.Now) < 0)
                            _queue.TryRemove(item.Key, out _);
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.LogError("StartListen", ex);
                    }
                }
                await Task.Delay(5000);
            }, TaskCreationOptions.LongRunning);
        }
        public bool GetStatus(string deviceId)
        {
            try
            {
                _queue.TryGetValue(deviceId, out var status);
                return status.CompareTo(DateTime.Now) >= 0;
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("GetStatus", ex);
                return false;
            }
        }
    }
}